<template>
  <el-card>
    <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>重置密码</el-breadcrumb-item>
    </el-breadcrumb>
    <el-form
      :model="pwdForm"
      ref="formRef"
      label-width="100px"
      style="width: 500px"
      :rules="rules"
    >
      <el-form-item label="原密码" prop="old_pwd">
        <el-input type="password" v-model="pwdForm.old_pwd"></el-input>
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="password" v-model="pwdForm.new_pwd"></el-input>
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input type="password" v-model="pwdForm.re_pwd"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updatePwd">修改密码</el-button>
        <el-button>重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>
<script>
import { reqUpdatePwd } from '../../api/user'
export default {
  name: 'UserPassword',
  data () {
    // 检验密码长度
    // 检验新密码是否和旧密码一致
    const checkNewPwd = (rule, value, cb) => {
      if (value === this.pwdForm.old_pwd) {
        return cb(new Error('新密码不能和原密码一致'))
      }
      cb()
    }

    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('输入不能为空，请再次输入密码'))
      } else if (value !== this.pwdForm.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      pwdForm: {
        old_pwd: '',
        new_pwd: '',
        re_pwd: ''
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符串',
            trigger: 'blur'
          }
        ],
        new_pwd: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          {
            pattern: /^\S{6,15}$/,
            message: '密码必须是6-15位的非空字符串',
            trigger: 'blur'
          },
          { validator: checkNewPwd, trigger: 'blur' }
        ],
        re_pwd: [
          {
            required: true,
            message: '请在此输入密码',
            trigger: ['blur', 'blur']
          },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    updatePwd () {
      this.$refs.formRef.validate(async (valid) => {
        if (valid) {
          const res = await reqUpdatePwd(this.pwdForm)
          if (res.data.code === 0) {
            // 清除token并重新登录
            localStorage.removeItem('token')
            this.$router.push('/login')
          }
        }
      })
    }
  }
}
</script>
